class YarnsController < ApplicationController
  
  before_filter :authorize
  
  layout :determine_layout
  
  def index
    list
    render :action => 'list'
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
    @yarn_pages, @yarns = paginate :yarns, :per_page => 10
  end

  def show
    @yarn = Yarn.find(params[:id])
    @container_pages, @containers = paginate :containers, :conditions => [ "yarn_id = ? AND container_state_id = ?", @yarn.id, ContainerState.find_by_code(0).id ], :per_page => 10
  end

  def new
    @yarn = Yarn.new
  end

  def create
    @yarn = Yarn.new(params[:yarn])
    if @yarn.save
      flash[:notice] = 'Yarn was successfully created.'
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
  end

  def edit
    @yarn = Yarn.find(params[:id])
  end

  def update
    @yarn = Yarn.find(params[:id])
    if @yarn.update_attributes(params[:yarn])
      flash[:notice] = 'Yarn was successfully updated.'
      redirect_to :action => 'show', :id => @yarn
    else
      render :action => 'edit'
    end
  end

  def destroy
    Yarn.find(params[:id]).destroy
    redirect_to :action => 'list'
  end
  
  def add_inventory
    Yarn.find(params[:id]).containers.create(params[:container])
    redirect_to :action => 'show', :id => params[:id]
  end
end
